﻿#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QDebug>
#include <QJsonArray>
#include "JZAgent.h"
#include "JZJsonHelper.h"

JZAgent::JZAgent()
{
    m_manager = new QNetworkAccessManager(this);
}

JZAgent::~JZAgent()
{
}

void JZAgent::addTool()
{

}

void JZAgent::addMessage(QJsonArray &array, Role role, QString content)
{
    QJsonObject message;
    message["role"] = (role == System)? "system" : "user";
    message["content"] = content;

    array.push_back(message);
}

bool JZAgent::send(QString content, QString &result)
{
    QUrl url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
    QString apiKey = "sk-c7cbd6d56e5049c69a640f9596c978d3";

    QJsonArray message;
    addMessage(message,System, "你是一个调色助手，用户请求颜色返回RGB值，一次只返回一个,返回格式 RGB(r,g,b),只输出颜色值，如果用户没提到颜色，返回NULL");
    addMessage(message,User, content);

    QJsonObject obj;
    obj["model"] = "qwen-plus";
    obj["messages"] = message;
    obj["stream"] = false;
    obj["modalities"] = QJsonArray{ "text" };
    obj["max_tokens"] = 128;

    QString authHeader = "Bearer " + apiKey;

    QNetworkRequest req;
    req.setUrl(url);
    req.setRawHeader("Authorization", authHeader.toUtf8());
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QByteArray buffer = QJsonDocument(obj).toJson();
    QNetworkReply* reply = m_manager->post(req, buffer);
    
    JZCoNetworkReply co_reply(reply);
    co_reply.waitFinish();

    if (reply->error() != QNetworkReply::NoError)
    {
        return false;
    }

    QJsonParseError json_error;
    QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &json_error);
    if (json_error.error != QJsonParseError::NoError)
        return false;

    QJsonObject ret_obj = doc.object();
    QJsonValue value;
    if (!JZJsonHelper::getValue(ret_obj, "choices[0].message.content", value))
        return false;

    result = value.toString();
    return true;
}